import datetime
from flask import Blueprint, make_response, request, jsonify
import jwt
from tool.db import sqlOp
from tool.config import config
import os

config = config.get_sync_config()

auth_bp = Blueprint('auth', __name__)

# users = {}

@auth_bp.route("/api/register", methods=["POST"])
def register():
    data = request.get_json()
    username = data.get("registerName")
    password = data.get("registerPassword")

    if not username or not password:
        return jsonify({"error": "用户名和密码不能为空"}), 400

    if sqlOp.login(username, password):
        return jsonify({"error": "用户名已存在"}), 409

    # users[username] = generate_password_hash(password)
    user_root = os.path.join(config["FILE_SYSTEM"]["UPLOAD_FOLDER"], username)
    user_vec_db = os.path.join(config["FILE_SYSTEM"]["CHROMA_DB"],username)
    os.makedirs(user_root, exist_ok=True)
    os.makedirs(user_vec_db, exist_ok=True)
    sqlOp.register(username, password)

    return jsonify({"message": "注册成功"}), 201

@auth_bp.route("/api/login", methods=["POST"])
def login():
    data = request.get_json()
    username = data.get("loginUsername")
    password = data.get("loginPassword")

    if not username or not password:
        return jsonify({"error": "用户名和密码不能为空"}), 400

    if not sqlOp.login(username,password):
        return jsonify({"error": "用户名或密码错误"}), 401

    token = jwt.encode({"user": username, "exp": datetime.datetime.utcnow() + datetime.timedelta(hours=1)},
                           config["FILE_SYSTEM"]["JWT_SECRET_KEY"], algorithm="HS256")
    # access_token = create_access_token(identity=username)
    resp = make_response(jsonify({"msg": "登录成功"}),200)
    resp.set_cookie("token", token, max_age=3600)  # 设置 HttpOnly=True 更安全
    return resp